package dk.modified.reshary;

import java.util.ArrayList;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.ExpandableListView.OnGroupExpandListener;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;

import dk.modified.reshary.GlobalState.TrackerName;
import dk.modified.reshary.ViewShare.onCategoryChanged;

public class MainActivity extends Activity {
	private DrawerLayout mDrawerLayout;
	private RelativeLayout mDrawerRelativeLayout;
	private CharSequence mDrawerTitle;
	private CharSequence mTitle;
	private ActionBarDrawerToggle mDrawerToggle;
	private static int currentposition;
	ExpandableListAdapter listAdapter;
	ExpandableListView expListView;
//	private ArrayList<Category> categoryArr;
	private ArrayList<Category> newCategoryArr;
	private long currentTime = 0;
	private int lastExpandedGroup;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		
		if(savedInstanceState != null){
			newCategoryArr = savedInstanceState.getParcelableArrayList("categoryArr");
		} else {
			if(getIntent().getParcelableArrayListExtra("categoryArr") != null){
				newCategoryArr = getIntent().getParcelableArrayListExtra("categoryArr");
			} else {
				Intent i = new Intent(this, SplashScreen.class);
				i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
						| Intent.FLAG_ACTIVITY_CLEAR_TASK);
				startActivity(i);
			}
		}
		
		

		Tracker t = ((GlobalState) getApplication())
				.getTracker(TrackerName.APP_TRACKER);
		t.setScreenName("Reshary MainActivity");
		t.send(new HitBuilders.AppViewBuilder().build());
		
		
		expListView = (ExpandableListView) findViewById(R.id.lvExp);
		currentposition = -2;

		mTitle = mDrawerTitle = getTitle();
		mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
		mDrawerRelativeLayout = (RelativeLayout) findViewById(R.id.relative_layout);
		mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
				GravityCompat.START);
		// Set the adapter for the list view
		// Set the list's click listenerr());

		getActionBar().setDisplayHomeAsUpEnabled(true);
		getActionBar().setHomeButtonEnabled(true);

		// ActionBarDrawerToggle ties together the the proper interactions
		// between the sliding drawer and the action bar app icon
		mDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */
		mDrawerLayout, /* DrawerLayout object */
		R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
		R.string.drawer_open, /* "open drawer" description for accessibility */
		R.string.drawer_close /* "close drawer" description for accessibility */

		) {
			public void onDrawerClosed(View view) {
				// getActionBar().setTitle(mTitle);
				Util.setActionBar(MainActivity.this, ((String) mTitle));
				invalidateOptionsMenu(); // creates call to
											// onPrepareOptionsMenu()
			}

			public void onDrawerOpened(View drawerView) {
				// getActionBar().setTitle(mDrawerTitle);
				Util.setActionBar(MainActivity.this, ((String) mDrawerTitle));
				invalidateOptionsMenu(); // creates call to
											// onPrepareOptionsMenu()
			}
		};
		mDrawerLayout.setDrawerListener(mDrawerToggle);

		selectItem(-1,0,null);
		try {
			GetCategories();
			expListView.setOnGroupClickListener(new OnGroupClickListener() {

				@Override
				public boolean onGroupClick(ExpandableListView parent, View v,
						int groupPosition, long id) {
					Category selectedCategory = newCategoryArr.get(groupPosition);

					if (selectedCategory.hasChild()) {

					} else {
						int index = expListView.getFlatListPosition(ExpandableListView
								.getPackedPositionForGroup(groupPosition));
						selectItem(index, selectedCategory.getCategoryId(),selectedCategory.getCategoryName());
					}
					return false;
				}
			});
			expListView.setOnChildClickListener(new OnChildClickListener() {

				@Override
				public boolean onChildClick(ExpandableListView parent, View v,
						int groupPosition, int childPosition, long id) {
					CategorySub selectedCategory = newCategoryArr.get(groupPosition)
							.getChildAtPosition(childPosition);
					

					int index = expListView
							.getFlatListPosition(ExpandableListView
									.getPackedPositionForChild(groupPosition,
											childPosition));

					selectItem(index,selectedCategory.getCategoryId(),selectedCategory.getCategoryName());

					return false;
				}
			});
			
		} catch (Exception e) {
			Intent i = new Intent(this, SplashScreen.class);
			i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
					| Intent.FLAG_ACTIVITY_CLEAR_TASK);
			startActivity(i);
		}

	}

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		// Sync the toggle state after onRestoreInstanceState has occurred.
		mDrawerToggle.syncState();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		// Pass any configuration change to the drawer toggls
		mDrawerToggle.onConfigurationChanged(newConfig);
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		// If the nav drawer is open, hide action items related to the content
		// view
		boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerRelativeLayout);
		menu.findItem(R.id.action_camera).setVisible(!drawerOpen);
		menu.findItem(R.id.action_browse).setVisible(!drawerOpen);
		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// The action bar home/up action should open or close the drawer.
		// ActionBarDrawerToggle will take care of this.
		if (mDrawerToggle.onOptionsItemSelected(item)) {
			return true;
		}
		// Handle action buttons
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onBackPressed() {

		RelativeLayout layout_reshare_slide = (RelativeLayout) findViewById(R.id.layout_reshare_slide);
		
		if(mDrawerLayout.isDrawerOpen(mDrawerRelativeLayout)){
			mDrawerLayout.closeDrawer(mDrawerRelativeLayout);
			return;
		}

		if (layout_reshare_slide.getVisibility() == View.VISIBLE) {
			FrameLayout image_container = (FrameLayout) findViewById(R.id.image_container);
			image_container.setTranslationX(0);
			image_container.clearAnimation();
			layout_reshare_slide.setVisibility(View.INVISIBLE);
			ViewShare.swipeOnImage = true;
		}

		else {

			if (currentTime == 0) {
				currentTime = System.currentTimeMillis();
				Toast.makeText(this,
						getResources().getString(R.string.are_you_sure),
						Toast.LENGTH_SHORT).show();
			} else {
				if ((System.currentTimeMillis() - currentTime) < 3000) {
					finish();
				} else {
					currentTime = System.currentTimeMillis();
					Toast.makeText(this,
							getResources().getString(R.string.are_you_sure),
							Toast.LENGTH_SHORT).show();
				}
			}

		}

	}

	private void selectItem(int positionSelected, int categoryId, String categoryName) {
		// VIEW SHARES
		if (positionSelected != currentposition) {

			if (positionSelected == -1) {
				Bundle args = new Bundle();
				args.putInt("cat_id", -1);
				args.putParcelableArrayList("categoryArr", newCategoryArr);
				ViewShare fragment = new ViewShare();
				fragment.setOnCategoryChangedListener(new onCategoryChanged() {

					@Override
					public void categoryChanged(int pos,int categoryId,String categoryName) {
						// TODO Auto-generated method stub
						expListView.clearChoices();
						int count =  listAdapter.getGroupCount();
						for (int i = 0; i <count ; i++)
							expListView.collapseGroup(i);
						expListView.requestLayout();
						selectItem(pos,0,null);
					}
				});
				fragment.setArguments(args);
				FragmentManager fragmentManager = getFragmentManager();

				fragmentManager.beginTransaction()
						.replace(R.id.content_frame, fragment).commit();
				currentposition = positionSelected;
				setTitle(getResources().getString(R.string.app_name));
			} else {

				Bundle args = new Bundle();
				args.putInt("cat_id", categoryId);
				args.putParcelableArrayList("categoryArr", newCategoryArr);

				ViewShare fragment = new ViewShare();
				fragment.setOnCategoryChangedListener(new onCategoryChanged() {

					@Override
					public void categoryChanged(int pos, int categoryId,String categoryName) {
						expListView.clearChoices();
						int count =  listAdapter.getGroupCount();
						for (int i = 0; i <count ; i++)
							expListView.collapseGroup(i);
						expListView.requestLayout();
						selectItem(pos,0,null);
						
					}
				});
				fragment.setArguments(args);
				FragmentManager fragmentManager = getFragmentManager();
				fragmentManager.beginTransaction()
						.replace(R.id.content_frame, fragment).commit();
				currentposition = positionSelected;
				expListView.setItemChecked(positionSelected, true);
				setTitle(categoryName);
			}

		}

		mDrawerLayout.closeDrawer(mDrawerRelativeLayout);
	}

	@Override
	public void setTitle(CharSequence title) {
		mTitle = title;
		Util.setActionBar(this, (String) title);
		// getActionBar().setTitle(mTitle);
	}

	public void aboutOnClick(View v) {
		Toast.makeText(this, "To be implemented...", Toast.LENGTH_SHORT).show();
		// Intent i = new Intent(this,About.class);
		// startActivity(i);
	}

	private void GetCategories() {
		listAdapter = new ExpandableListAdapter(MainActivity.this,
				newCategoryArr);
		expListView.setAdapter(listAdapter);
		listAdapter.notifyDataSetChanged();
	}

	public void logoutOnClick(View v) {
		SharedPreferences sharedpreferences = getSharedPreferences(
				"dk.modified.reshary", Context.MODE_PRIVATE);
		Editor editor = sharedpreferences.edit();
		editor.putString("securitytoken", "null");
		editor.putString("userid", "null");
		editor.commit();

		Intent loginscreen = new Intent(getApplicationContext(),
				LoginOrSignup.class);
		loginscreen.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
				| Intent.FLAG_ACTIVITY_CLEAR_TASK);
		startActivity(loginscreen);
	}


	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onRestoreInstanceState(savedInstanceState);
		newCategoryArr = savedInstanceState.getParcelableArrayList("categoryArr");
		listAdapter = new ExpandableListAdapter(MainActivity.this,
				newCategoryArr);
		expListView.setAdapter(listAdapter);
		listAdapter.notifyDataSetChanged();
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		// TODO Auto-generated method stub
		super.onSaveInstanceState(outState);
		outState.putParcelableArrayList("categoryArr", newCategoryArr);
	}


	
	
	

}
